package com.banksoft.front.controller;

import com.banksoft.admin.SystemCache;
import com.banksoft.admin.dao.ProductDao;
import com.banksoft.admin.entity.Product;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.service.BaseService;
import com.banksoft.common.BaseController;
import com.banksoft.common.ConfigHelper;
import com.banksoft.front.util.WeixinUtil;
import com.banksoft.util.StringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by vanjoger on 2017/1/6.
 */
@Controller
@RequestMapping("/front")
public class FrontWxSettingController extends BaseController{

    private Logger logger = LoggerFactory.getLogger(FrontWxSettingController.class);

    private String shareUrl = "/wx/index";

    @Autowired
    BaseService baseService;

    @RequestMapping("/getShareConfig")
    @ResponseBody
    public JSONObject getShareConfig(HttpServletRequest request,String url,String productId){
        try{
            ConfigHelper instance = ConfigHelper.GetInstance();
            String shareTitle = instance.GetConfig("ShareTitle");
            String shareDesc = instance.GetConfig("ShareDesc");
            String shareImg = instance.GetConfig("ShareImg");
            Product product = this.baseService.findById(ProductDao.class,productId);
            if(product!=null){
                shareTitle = product.getDescription();
                String images = product.getImages();
                if(StringUtil.isNotNull(images)) {
                    String[] arrays = images.split("\\|");
                    shareImg = arrays[0];
                }
            }
            String access_token = WeixinUtil.createAccess_token();
            String jsapi_ticket = WeixinUtil.createJsapi_ticket(access_token);
            String nonceStr = WeixinUtil.create_nonce_str();
            String timestamp = WeixinUtil.create_timestamp();
            logger.info("share data ::  "+url+" : "+jsapi_ticket+" : "+nonceStr+" : "+ String.valueOf(timestamp));
            String signature = sign(jsapi_ticket, url, nonceStr, String.valueOf(timestamp));

            User user = (User) request.getSession().getAttribute(SystemCache.SESSION_USER);

            String redirectUrl = "http://boaishangcheng.com/wx/index";
            String lineLink = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + SystemCache.AppId +
                    "&redirect_uri=" + redirectUrl + "&response_type=code" +
                    "&scope=snsapi_userinfo&state="+user.getId()+"#wechat_redirect";

            Map map = new HashMap();
            map.put("nonceStr",nonceStr);
            map.put("timestamp",timestamp);
            map.put("signature",signature);
            map.put("shareTitle",shareTitle);
            map.put("shareDesc",shareDesc);
            map.put("shareImg",shareImg);
            map.put("appId", SystemCache.AppId);
            map.put("lineLink",lineLink);

            return this.FmtResult(true,null,map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return this.FmtResult(false,"加载配置失败",null);
    }



    public String sign(String jsapi_ticket, String url, String nonce_str, String timestamp) {
        String string1;
        String signature = "";

        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp + "&url=" + url;
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }catch (Exception e) {
            e.printStackTrace();
        }

        return signature;
    }



    private String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
